package org.dromara.comm.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.comm.domain.AsLabel;
import org.dromara.comm.domain.AsLeaveIdle;
import org.dromara.comm.domain.AsLeaveIdleImage;
import org.dromara.comm.domain.AsUserLeaveIdle;
import org.dromara.comm.mapper.AsLabelMapper;
import org.dromara.comm.mapper.AsLeaveIdleImageMapper;
import org.dromara.comm.mapper.AsLeaveIdleMapper;
import org.dromara.comm.mapper.AsUserLeaveIdleMapper;
import org.dromara.comm.service.AsLabelService;
import org.dromara.comm.service.AsLeaveIdleService;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发闲置业务层
 *
 * @author: 郭伟明
 * @date: 2024-08-05 09:55
 **/
@Service
public class AsLeaveIdleServiceImpl extends ServiceImpl<AsLeaveIdleMapper, AsLeaveIdle> implements AsLeaveIdleService {

    @Autowired
    private AsLeaveIdleMapper asLeaveIdleMapper;

    @Autowired
    private AsLeaveIdleImageMapper asLeaveIdleImageMapper;

    @Autowired
    private AsLabelService asLabelService;

    @Autowired
    private AsLabelMapper asLabelMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AsUserLeaveIdleMapper asUserLeaveIdleMapper;


    @Override
    public Page<AsLeaveIdle> selectAsLeaveIdle(AsLeaveIdle asLeaveIdle, Pageable pageable) {
        Page<AsLeaveIdle> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
        LambdaQueryWrapper<AsLeaveIdle> wrapper = new LambdaQueryWrapper<>();
        if (asLeaveIdle != null){
            wrapper.like(AsLeaveIdle::getProductName, asLeaveIdle.getProductName());
            wrapper.eq(AsLeaveIdle::getStatus,0);
        }
        if (asLeaveIdle.getStatus()==1){
            wrapper.eq(AsLeaveIdle::getStatus, asLeaveIdle.getStatus());
        }
        Page<AsLeaveIdle> asLeaveIdlePage = asLeaveIdleMapper.selectPage(page, wrapper);
        return asLeaveIdlePage;
    }

    @Override
    public void insertAsLeaveIdleImages(AsLeaveIdle asLeaveIdle, AsLeaveIdleImage asLeaveIdleImage, List<AsLabel> labelIds) {
        AsLeaveIdleImage leaveIdleImage = asLeaveIdleImageMapper.selectById(asLeaveIdleImage.getId());
        if (leaveIdleImage != null) {
            AsLeaveIdle idle = new AsLeaveIdle();
            idle.setProductName(asLeaveIdle.getProductName());
            idle.setDescription(asLeaveIdle.getDescription());
            idle.setSellingPrice(asLeaveIdle.getSellingPrice());
            idle.setCostPrice(asLeaveIdle.getCostPrice());
            idle.setAddress(asLeaveIdle.getAddress());
            asLeaveIdle.setThumbnail(leaveIdleImage.getUrl());
            asLeaveIdleMapper.insert(idle);
            for (AsLabel labelId : labelIds) {
                AsLabel asLabel = new AsLabel();
                asLabel.setLabel_id(asLeaveIdle.getId()+0L);
                asLabel.setLabel(labelId.getLabel());
                List<AsLabel> list = new ArrayList<>();
                list.add(asLabel);
                asLabelService.saveBatch(list);
            }
        }
    }

    @Override
    public void updateAsLeaveIdleImages(AsLeaveIdle asLeaveIdle, AsLeaveIdleImage asLeaveIdleImage, List<AsLabel> labelIds) {
        AsLeaveIdleImage leaveIdleImage = asLeaveIdleImageMapper.selectById(asLeaveIdleImage.getId());
        if (leaveIdleImage != null) {
            AsLeaveIdle idle = new AsLeaveIdle();
            idle.setProductName(asLeaveIdle.getProductName());
            idle.setDescription(asLeaveIdle.getDescription());
            idle.setSellingPrice(asLeaveIdle.getSellingPrice());
            idle.setCostPrice(asLeaveIdle.getCostPrice());
            idle.setAddress(asLeaveIdle.getAddress());
            asLeaveIdle.setThumbnail(leaveIdleImage.getUrl());
            asLeaveIdleMapper.updateById(idle);
            for (AsLabel labelId : labelIds) {
                AsLabel asLabel = new AsLabel();
                asLabel.setLabel_id(asLeaveIdle.getId()+0L);
                asLabel.setLabel(labelId.getLabel());
                List<AsLabel> list = new ArrayList<>();
                list.add(asLabel);
                asLabelService.updateBatchById(list);
            }
        }
    }


    public List<AsLeaveIdle> getAllDigitalToys() {
        List<AsLeaveIdle> allToys = asLeaveIdleMapper.selectList(null);
        return buildTree(allToys);
    }

    public List<AsLeaveIdle> getDigitalToysByCategory(String categoryId) {
        List<AsLeaveIdle> toysByCategory = asLeaveIdleMapper.selectByCategoryId(categoryId);
        return buildTree(toysByCategory);
    }


    private List<AsLeaveIdle> buildTree(List<AsLeaveIdle> toys) {
        Map<String, List<AsLeaveIdle>> categoryMap = new HashMap<>();

        // 填充分类信息
        for (AsLeaveIdle toy : toys) {
            String category = toy.getCategoryId();
            categoryMap.putIfAbsent(category, new ArrayList<>());
            categoryMap.get(category).add(toy);
        }

        // 组织树形结构
        List<AsLeaveIdle> tree = new ArrayList<>();
        for (Map.Entry<String, List<AsLeaveIdle>> entry : categoryMap.entrySet()) {
            AsLeaveIdle categoryNode = new AsLeaveIdle();
            categoryNode.setCategory(entry.getKey());
            categoryNode.setChildren(entry.getValue());
            tree.add(categoryNode);
        }

        return tree;
    }

    @Override
    public List<AsLeaveIdle> details(AsLeaveIdle asLeaveIdle) {
        // Fetch the main AsLeaveIdle entity by ID
        AsLeaveIdle asLeaveIdles = asLeaveIdleMapper.selectById(asLeaveIdle.getId());

        // Check if the main entity is null
        if (asLeaveIdles == null) {
            return new ArrayList<>(); // Return an empty list or handle this case as needed
        }

        // Fetch associated SysUsers based on userId
        LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(SysUser::getUserId, asLeaveIdles.getUserId());
        List<SysUser> sysUsers = sysUserMapper.selectList(userWrapper);
        asLeaveIdles.setSysUsers(sysUsers);

        // Fetch associated AsLabels based on the leave idle ID
        LambdaQueryWrapper<AsLabel> labelWrapper = new LambdaQueryWrapper<>();
        labelWrapper.eq(AsLabel::getLabel_id, asLeaveIdles.getId());
        List<AsLabel> asLabels = asLabelMapper.selectList(labelWrapper);
        asLeaveIdles.setAsLabels(asLabels);

        // Fetch associated AsLeaveIdleImages based on the leave idle ID
        LambdaQueryWrapper<AsLeaveIdleImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(AsLeaveIdleImage::getImageId, asLeaveIdles.getId());
        List<AsLeaveIdleImage> asLeaveIdleImages = asLeaveIdleImageMapper.selectList(imageWrapper);
        asLeaveIdles.setAsLeaveIdleImages(asLeaveIdleImages);

        // Return the list containing the populated AsLeaveIdle object
        List<AsLeaveIdle> result = new ArrayList<>();
        result.add(asLeaveIdles);
        return result;
    }

    /**
     * 下架或上架
     * @param asLeaveIdle
     */
    @Override
    public void updateState(AsLeaveIdle asLeaveIdle) {
        asLeaveIdleMapper.updateById(asLeaveIdle);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteIsDelete(Integer id) {
        asLeaveIdleMapper.deleteById(id);
    }

    @Override
    public Map<String,Object> selectAsMyRelease(AsLeaveIdle asLeaveIdle, Pageable pageable) {
        Map<String, Object> map = new HashMap<>();
        Page<AsLeaveIdle> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
        if (asLeaveIdle.getState()==0) {
            LambdaQueryWrapper<AsLeaveIdle> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AsLeaveIdle::getIsDelete, 0);
            Page<AsLeaveIdle> selectPage = asLeaveIdleMapper.selectPage(page, wrapper);
            map.put("data", selectPage.getRecords());
        }else {
            LambdaQueryWrapper<AsLeaveIdle> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AsLeaveIdle::getIsDelete, 1);
            Page<AsLeaveIdle> selectPage = asLeaveIdleMapper.selectPage(page, wrapper);
            map.put("data", selectPage.getRecords());
        }
        return map;
    }

    @Override
    public void updateStates(AsLeaveIdle asLeaveIdle) {
        if (asLeaveIdle.getState()==0){
            AsLeaveIdle release = new AsLeaveIdle();
            release.setState(1);
            asLeaveIdleMapper.updateById(release);
        }else {
            AsLeaveIdle release = new AsLeaveIdle();
            release.setState(0);
            asLeaveIdleMapper.updateById(release);
        }
    }

    @Override
    public void updateIsDelete(AsLeaveIdle asLeaveIdle) {
        if (asLeaveIdle.getState()==0){
            asLeaveIdleMapper.deleteById(asLeaveIdle.getId());
        }else {
            asLeaveIdleMapper.deleteById(asLeaveIdle.getId());
        }
    }

    @Override
    public void insertCollection(AsLeaveIdle asLeaveIdle) {
        AsUserLeaveIdle asUserLeaveIdle = new AsUserLeaveIdle();
        asUserLeaveIdle.setUserId(LoginHelper.getUserId());
        asUserLeaveIdle.setLeaveIdleId(asLeaveIdle.getId()+0L);
        asUserLeaveIdle.setState(1);
        asUserLeaveIdleMapper.insert(asUserLeaveIdle);
    }

    @Override
    public List<Object> selectAsUserLeaveIdle(AsUserLeaveIdle asUserLeaveIdle) {
        List<Object> arrayList = new ArrayList<>();
        SysUser selectById = sysUserMapper.selectById(LoginHelper.getUserId());
            LambdaQueryWrapper<AsUserLeaveIdle> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AsUserLeaveIdle::getUserId,selectById.getUserId());
            wrapper.eq(AsUserLeaveIdle::getState,1);
            List<AsUserLeaveIdle> asUserLeaveIdles = asUserLeaveIdleMapper.selectList(wrapper);
            for (AsUserLeaveIdle userLeaveIdle : asUserLeaveIdles) {
                LambdaQueryWrapper<AsLeaveIdle> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AsLeaveIdle::getId,userLeaveIdle.getLeaveIdleId());
                List<AsLeaveIdle> asLeaveIdles = asLeaveIdleMapper.selectList(queryWrapper);
                arrayList.add(asLeaveIdles);
            }
        return arrayList;
    }

}
